export default {
	namespaced:true,
	
	state:()=>({
		cart:JSON.parse(uni.getStorageSync('cart')||'[]')
	}),
	
	mutations:{
		removeGoodsById(state,goodsId){
			state.cart = state.cart.filter(x=>x.goods_id !==goodsId)
			this.commit('m_cart/saveToStorage')
		},
		updateGoodsCount(state,goods){
			const findresult = state.cart.find(x=>x.goods_id ===goods.goods_id)
			if(findresult){
				findresult.goods_count = goods.goods_count
				this.commit('m_cart/saveToStorage')
			}
		},
		updateGoodsState(state,goods){
			const findresult = state.cart.find(x=>x.goods_id ===goods.goods_id)
			if(findresult){
				findresult.goods_state = goods.goods_state
				this.commit('m_cart/saveToStorage')
			}
		},
		addToCart(state,goods){
			const findresult = state.cart.find(x=>x.goods_id ===goods.goods_id)
			if(!findresult){
				state.cart.push(goods)
			}else{
				findresult.goods_count++
			}
			this.commit('m_cart/saveToStorage')
			// console.log(state.cart)
		},
		updateAllGoodsState(state,goods_state){
			// console.log(goods_state)
			state.cart.forEach(x=>x.goods_state=goods_state)
			this.commit('m_cart/saveToStorage')
		},
		saveToStorage(state){
			uni.setStorageSync('cart',JSON.stringify(state.cart))
		}
	},
	
	getters:{
		total(state){
			let c =0;
			state.cart.forEach(x => c += x.goods_count)
			return c
		},
		checkedCount(state){
			return state.cart.filter(x => x.goods_state).reduce((total,item)=>{return total+=item.goods_count},0)
		},
		checkedGoodsAmount(state){
			return state.cart.filter(x => x.goods_state)
			.reduce((total,item)=>total+=(item.goods_count*item.goods_price),0)
			.toFixed(2)
		}
	}
	
}